package com.songlanyun.modules.shop.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import com.songlanyun.common.annotation.RepeatSubmit;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.common.utils.Constant;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.common.validator.ValidatorUtils;
import com.songlanyun.common.validator.group.AddGroup;
import com.songlanyun.common.validator.group.UpdateGroup;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.applyareaagent.service.ApplyAreaAgentService;
import com.songlanyun.modules.exception.ShopException;
import com.songlanyun.modules.shop.entity.ShopAdminRelationEntity;
import com.songlanyun.modules.shop.entity.ShopApplyEntity;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.model.dto.ShopApplyDTO;
import com.songlanyun.modules.shop.model.dto.ShopDTO;
import com.songlanyun.modules.shop.model.dto.ShopRateDTO;
import com.songlanyun.modules.shop.model.vo.ShopInfoVO;
import com.songlanyun.modules.shop.model.vo.ShopVO;
import com.songlanyun.modules.shop.service.ShopAdminRelationService;
import com.songlanyun.modules.shop.service.ShopApplyService;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.user.controller.AbstractController;
import com.songlanyun.modules.user.entity.SysUserEntity;
import com.songlanyun.modules.user.entity.SysUserEntityDTO;
import com.songlanyun.modules.user.exception.UserException;
import com.songlanyun.modules.user.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Arrays;
import java.util.Map;


/**
 * 商家表
 *
 * @author Mark
 * @email sunlightcs@gmail.com
 * @date 2020-11-03 14:34:03
 */
@RestController
@RequestMapping("admin/yxt/shop")
public class ShopAdminController extends AbstractController {
    @Resource
    private ShopService shopService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private AccountService accountService;
    @Resource
    private ShopApplyService shopApplyService;
    @Resource
    private ApplyAreaAgentService applyAreaAgentService;

    /**
     * 商家列表
     */
    @GetMapping("/list")
//    @RequiresPermissions("shop:yxtshop:list")
    public R list(@RequestParam Map<String, Object> params) {
        //设置区县代理参数
        if (getAreaAgentId() != 0L) {
            applyAreaAgentService.setAreaAgentParams(getAreaAgentId(), params);
        }
        PageUtils page = shopService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 商家查询自己的商家信息
     */
    @GetMapping("/getShopInfo")
//    @RequiresPermissions("shop:yxtshop:list")
    public R getShopInfo() {
        Long shopId = getShopId(false);
        if (shopId == 0) {//平台管理员查询平台店铺
            shopId = shopService.selectPlatformShopId(true);
        }
        ShopInfoVO vo = shopService.getShopInfo(shopId);
        return R.ok().put("data", vo);
    }

    /**
     * 获取当前店铺
     */
    @GetMapping("/getShop")
//    @RequiresPermissions("shop:yxtshop:list")
    public R getShop() {
        Long shopId = getShopId(false);
        //如果是平台管理员，则返回null
        if (shopId == 0) {
            return R.ok().put("data", null);
        }
        ShopInfoVO vo = shopService.getShopInfo(shopId);
        return R.ok().put("data", vo);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
//    @RequiresPermissions("shop:yxtshop:info")
    public R info(@PathVariable("id") Long id) {
        ShopInfoVO shop = shopService.getShopInfo(id);
        return R.ok().put("data", shop);
    }

    /**
     * 商家创建商家子管理员
     */
    @SysLog("商家创建商家子管理员")
    @PostMapping("/saveShopAdmin")
//    @RequiresPermissions("sys:user:save")
    public R saveShopAdmin(@RequestBody SysUserEntity user) {
        if (!getUser().getIsShop()) {//商家管理员操作
            return R.error(UserException.ADMIN_OPERATION.getMsg());
        }
        ValidatorUtils.validateEntity(user, AddGroup.class);
        //检验用户名和手机号
        sysUserService.verifyUserName(user.getUsername(), user.getMobile());

        user.setCreateUserId(getUserId());//设置创建人ID

        boolean isShop = getUser().getIsShop();
        Long shopId = getShopId();

        shopService.saveShopAdmin(user, shopId, isShop);

        return R.ok();

    }


    /**
     * 修改商家信息
     */
    @SysLog("修改商家信息")
    @PutMapping("/update")
//    @RequiresPermissions("shop:yxtshop:update")
    public R update(@RequestBody ShopDTO dto) {
        ValidatorUtils.validateEntity(dto);
        //更新商家信息
        ShopEntity shop = shopService.getById(dto.getId(), true);
        BeanUtil.copyPropertiesIgnoreNull(dto, shop);
        shopService.updateById(shop);

        return R.ok();
    }

    /**
     * 查询当前用户的店铺
     */
    @GetMapping("/adminShop")
    public R adminShop() {
        Long shopId = getShopId(false);
        if (shopId == 0) {//平台管理员查询平台店铺
            shopId = shopService.selectPlatformShopId(false);
            if (ObjectUtil.isNull(shopId)) {
                return R.ok();
            }
        }
        ShopInfoVO vo = shopService.getShopInfo(shopId);

        if (vo != null) {
            //查询店铺对应会员的邀请码
            String code = accountService.getCodeById(vo.getUserId());
            vo.setInvitationCode(code);
            //设置管理员id
            vo.setAdminId(shopService.getAdminPriByShopId(vo.getId()));
        }

        return R.ok().put("data", vo);
    }

    /**
     * 平台要初始化自己的店铺
     * <p>
     * shopEntity : 平台初始化时，需要填写的平台商家信息
     */
    @SysLog("平台初始化自己的店铺")
    @PostMapping("/initializeShop")
    @RepeatSubmit(value = "3")
    public R initializeShop(@RequestBody ShopApplyDTO dto) {

        ValidatorUtils.validateEntity(dto);
        //查询平台管理员有没有初始化过自己的店铺
        ShopEntity shop = shopService.selectPlatformShop();

        if (shop != null) {
            //已初始化过店铺，则更新平台企业信息和店铺信息
            shopService.updateByShopAllInfo(dto, shop);

        } else {
            //初始化
            if (dto.getUser() != null) {
                dto.getUser().setCreateUserId(getUserId());//设置创建人ID
            }
            shopService.initializeShop(dto);
        }

        return R.ok();
    }

    /**
     * 平台修改商家
     */
    @SysLog("平台修改商家")
    @RepeatSubmit("3")
    @PutMapping("/updateShop")
    public R updateShop(@RequestBody ShopEntity shopEntity) {
        verifyAdmin();//平台才能操作
        if (ObjectUtil.isNull(shopEntity.getId())) {
            throw new RRException(ShopException.MUST_PARAMETER_NOT_NULL);
        }
        shopService.updateShop(shopEntity);
        return R.ok();
    }


    /**
     * 平台为商家分配管理员账号
     */
    @SysLog("平台为商家分配管理员账号")
    @PostMapping("/assignedAccount")
    public R assignedAccount(@RequestBody SysUserEntityDTO user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
        verifyAdmin();

        //查询该商家信息
        ShopEntity shop = shopService.getById(user.getShopId(), true);

        SysUserEntity entity = sysUserService.selectShopAdmin(shop.getId(), false);
        //商家已分配管理员账号
        if (entity != null) {
            throw new RRException(UserException.ASSIGNED_ADMINISTRATOR);
        }

        //校验用户名和手机号
        sysUserService.verifyUserName(user.getUsername(), user.getMobile());

        //分配账号
        user.setCreateUserId(getUserId());//创建人ID
        shopService.assignedAccount(shop, user);

        return R.ok();
    }

    /**
     * 修改管理员账号
     */
    @SysLog("修改管理员账号")
    @RequestMapping("/updateUser")
    public R update(@RequestBody SysUserEntityDTO dto) {
        ValidatorUtils.validateEntity(dto, UpdateGroup.class);

        SysUserEntity user = sysUserService.getById(dto.getUserId());
        if (user == null) {
            throw new RRException(UserException.USER_NOT_EXISTS);
        }

        //校验用户名
        if (!user.getUsername().equals(dto.getUsername())) {
            sysUserService.verifyUserName(dto.getUsername());
        }
        //校验手机号
        if (!user.getMobile().equals(dto.getMobile())) {
            sysUserService.verifyMobile(dto.getMobile());
        }

        BeanUtil.copyPropertiesIgnoreNull(dto, user);
        //防止重置密码
        if (StringUtils.isBlank(dto.getPassword())) {
            user.setPassword(null);
        }
        sysUserService.update(user);

        return R.ok();
    }


    /**
     * 平台重置商家密码
     */
    @SysLog("平台为商家分配管理员账号")
    @PostMapping("/resetShopPassword")
    public R resetShopPassword(@RequestBody Long shopId) {
        verifyAdmin();
        shopService.resetShopPassword(shopId);

        return R.ok();

    }

    /**
     * 平台重置商家的提现手续费率
     */
    @SysLog("平台重置商家的提现手续费率")
    @PostMapping("/setCommissionRate")
    public R setCommissionRate(@RequestBody ShopRateDTO dto) {
        verifyAdmin();
        shopService.setCommissionRate(dto);
        return R.ok();

    }

    /**
     * 根据商家查询管理员主账号
     */
    @SysLog("根据商家查询管理员主账号")
    @GetMapping("/getShopAdmin/{shopId}")
    public R getShopAdmin(@PathVariable("shopId") Long shopId) {

        SysUserEntity user = shopService.getAdminByShopId(shopId);

        return R.ok().put("data", user);

    }

    /**
     * 平台显示隐藏商家
     */
    @SysLog("平台显示隐藏商家")
    @PostMapping("/show/{shopId}")
    public R show(@PathVariable("shopId") Long shopId) {
        verifyAdmin();
        shopService.show(shopId);
        return R.ok();
    }

}
